package com.tsfyun.scm.service.impl.support;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.tsfyun.common.base.dto.ExportFileDTO;
import com.tsfyun.common.base.exception.ServiceException;
import com.tsfyun.common.base.security.SecurityUtil;
import com.tsfyun.common.base.util.LocalDateTimeUtils;
import com.tsfyun.common.base.util.TypeUtils;
import com.tsfyun.scm.entity.customer.Customer;
import com.tsfyun.scm.entity.wms.ReceivingNote;
import com.tsfyun.scm.service.customer.ICustomerService;
import com.tsfyun.scm.service.file.IExportFileService;
import com.tsfyun.scm.service.support.IPdfService;
import com.tsfyun.scm.service.wms.IReceivingNoteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Optional;

/**
 * @Description: PDF操作服务实现类
 * @since Created in 2020/4/28 10:31
 */
@RefreshScope
@Slf4j
@Service
public class PdfServiceImpl implements IPdfService {

    @Autowired
    private IReceivingNoteService receivingNoteService;

    @Autowired
    private ICustomerService customerService;

    @Autowired
    private IExportFileService exportFileService;

    @Value("${file.directory}")
    private String filePath;

    @Override
    public Long printReceivingNoteLabel(Long id) {
        ReceivingNote receivingNote = receivingNoteService.getById(id);
        Optional.ofNullable(receivingNote).orElseThrow(()->new ServiceException("入库单数据不存在"));
        Integer caseNumber = TypeUtils.castToInt(receivingNote.getTotalCartonNum(),0) <= 0 ? 1 :  receivingNote.getTotalCartonNum();
        Customer customer = customerService.getById(receivingNote.getCustomerId());
        String receivingNoteNo = receivingNote.getDocNo();
        String customerName = customer.getName();
        String customerCode = customer.getCode();
        String tempPath = filePath + "temp" + File.separator + "scm"  + File.separator;
        File savePath = new File(tempPath);
        if(!savePath.exists()) {
            savePath.mkdirs();
        }
        String sysFileName =  String.format("%s-%s.pdf",receivingNote.getDocNo(), LocalDateTimeUtils.formatTime(LocalDateTime.now(),"yyyyMMddHHmmssSSS"));
        String filePath = tempPath + sysFileName;
        log.info("入库单【{}】，共【{}】箱",receivingNote.getDocNo(),caseNumber);
        BaseFont font = null;
        try {
            font = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
        } catch (DocumentException | IOException e) {
            log.error("创建字体异常",e);
            throw new ServiceException("系统创建pdf文档字体异常");
        }
        Document document = new Document(new RectangleReadOnly(283.461732F,141.7294512F));
        document.setMargins(13,20,20,20);
        Font textFont = new Font(font, 14, Font.BOLD, BaseColor.BLACK);
        PdfWriter writer = null;
        try {
            writer = PdfWriter.getInstance(document,new FileOutputStream(filePath));
        } catch (DocumentException | FileNotFoundException e) {
            log.error("系统不存在该文件目录异常",e);
            throw new ServiceException(String.format("系统不存在文件目录【%s】",savePath));
        }
        document.open();
        Paragraph content;
        PdfPCell cell;
        try {
            for (int i = 0; i <= caseNumber; i++) {
                //客户名称
                content = new Paragraph(customerName, textFont);
                content.setAlignment(Element.ALIGN_CENTER);
                document.add(content);

                //客户编号
                content = new Paragraph(customerCode, textFont);
                content.setAlignment(Element.ALIGN_CENTER);
                document.add(content);

                //入库单号
                content = new Paragraph(receivingNoteNo, textFont);
                content.setAlignment(Element.ALIGN_CENTER);
                document.add(content);

                //箱号表格
                PdfPTable table = new PdfPTable(new float[]{35F, 65F});
                table.setWidthPercentage(100);
                table.setSpacingBefore(2);
                table.setHorizontalAlignment(Element.ALIGN_MIDDLE);

                content = new Paragraph("箱号", textFont);
                cell = new PdfPCell();
                cell.setPhrase(content);
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);

                content = new Paragraph(String.valueOf(i), textFont);
                cell = new PdfPCell();
                cell.setPhrase(content);
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);

                content = new Paragraph("总箱数", textFont);
                cell = new PdfPCell();
                cell.setPhrase(content);
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);

                content = new Paragraph(String.valueOf(caseNumber), textFont);
                cell = new PdfPCell();
                cell.setPhrase(content);
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);

                document.add(table);
                document.newPage();
            }
        } catch (DocumentException e) {
            log.error("创建pdf文档异常",e);
            throw new ServiceException("生成pdf文档异常");
        }
        document.close();
        writer.flush();
        writer.close();
        //保存导出信息
        ExportFileDTO exportFileDTO = new ExportFileDTO();
        exportFileDTO.setPath(filePath);
        exportFileDTO.setFileName(sysFileName);
        exportFileDTO.setOnce(Boolean.TRUE);
        exportFileDTO.setOperator(SecurityUtil.getCurrentPersonName());
        return exportFileService.save(exportFileDTO);
    }

}
